package com.xiaoge;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.baomidou.mybatisplus.generator.fill.Property;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

/**
 * @description: 代码生成器
 * @author: Mr.Nie
 * @create: 2022-05-18 10:14
 **/
public class CodeGenerator {

    public static void main(String[] args) {
        /*数据库配置*/
        DataSourceConfig dataSourceConfig =
                new DataSourceConfig
                        .Builder("jdbc:mysql://localhost:3306/ayedu?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true","root","123456")
                        .dbQuery(new MySqlQuery())
                        .build();


        /*创建一共代码生成器对象*/
        AutoGenerator generator = new AutoGenerator(dataSourceConfig);



        //String property = System.getProperty(scanner("请输入项目路径"));


        /*全局配置*/
        GlobalConfig globalConfig = new GlobalConfig.Builder()
                .fileOverride()
                .outputDir(scanner("请输入你的项目路径") + "/src/main/java")
                .author("XiaoGe").disableOpenDir()
                //.enableKotlin()
                //.enableSwagger()
                .dateType(DateType.ONLY_DATE)
                .commentDate("yyyy-MM-dd")
                .build();



        generator.global(globalConfig);


        /*包配置(PackageConfig)*/
        PackageConfig packageConfig = new PackageConfig.Builder()
                .parent("com.xiaoge")
                //.moduleName("blog")
                .entity("entity")
                .service("service")
                .serviceImpl("service.impl")
                .mapper("mapper")
                .xml("mapper")
                .controller("controller")
                //.other("other")
                //.pathInfo(Collections.singletonMap(OutputFile.mapper, "D://"))
                //.pathInfo(Collections.singletonMap(OutputFile.xml, "D://"))
                .build();

        generator.packageInfo(packageConfig);


        TemplateConfig templateConfig = new TemplateConfig.Builder()
                .disable(TemplateType.ENTITY)
                .entity("/templates/entity.java")
                .service("/templates/service.java")
                .serviceImpl("/templates/serviceImpl.java")
                .mapper("/templates/mapper.java")
                .xml("/templates/mapper.xml")
                .controller("/templates/controller.java")
                .build();

        generator.template(templateConfig);

        /*策略配置*/
        StrategyConfig strategyConfig = new StrategyConfig.Builder()
                .enableCapitalMode()
                .enableSkipView()
                .disableSqlFilter()
                //.likeTable(new LikeTable("USER"))
                .addInclude(getTables(scanner("请输入表名，多个英文逗号分隔？所有输入 all")))
                .addTablePrefix("tb_", "biz_","edu_")
                //.addFieldSuffix("_flag")
                /*   .entityBuilder()
                   .controllerBuilder()
                   .mapperBuilder()
                   .serviceBuilder()*/
                .build();

        strategyConfig.entityBuilder()
                //.superClass(BaseEntity.class)
                .disableSerialVersionUID()
                .enableChainModel()
                .enableLombok()
                .enableRemoveIsPrefix()
                .enableTableFieldAnnotation()
                .enableActiveRecord()
                .versionColumnName("version")
                .versionPropertyName("version")
                .logicDeleteColumnName("deleted")
                .logicDeletePropertyName("deleted")
                .naming(NamingStrategy.underline_to_camel)
                .columnNaming(NamingStrategy.underline_to_camel)
                //.addSuperEntityColumns("id", "created_by", "created_time", "updated_by", "updated_time")
                //.addIgnoreColumns("age")
                .addTableFills(new Column("create_time", FieldFill.INSERT))
                .addTableFills(new Property("update_time", FieldFill.INSERT_UPDATE))
                .idType(IdType.AUTO)
                .formatFileName("%s")
                .build();

        strategyConfig.controllerBuilder()
                //.superClass(BaseController.class)
                //.enableHyphenStyle()
                .enableRestStyle()
                .formatFileName("%sController")
                .build();

        strategyConfig.serviceBuilder()
                //.superServiceClass(BaseService.class)
                // .superServiceImplClass(BaseServiceImpl.class)
                .formatServiceFileName("%sService")
                .formatServiceImplFileName("%sServiceImpl")
                .build();

        strategyConfig
                .mapperBuilder()
                .superClass(BaseMapper.class)
                //.enableMapperAnnotation()
                //.enableBaseResultMap()
                //.enableBaseColumnList()
                //.cache(MyMapperCache.class)
                .formatMapperFileName("%sMapper")
                .formatXmlFileName("%sMapper")
                .build();


        generator.strategy(strategyConfig);

        /*执行代码生成器*/
        generator.execute();
    }

    // 处理 all 情况
    protected static List<String> getTables(String tables) {
        return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
    }

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }
}
